﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Web;
using System.Text;

namespace Facebook
{
    /// <summary>
    /// Class to handle  parameters and internet communication for the facebook REST-like service
    /// </summary>
    public static class Web
    {
        /// <summary>
        /// Takes a SortedDictionary of input parameters and returns a formatted string ready for passing to the facebook web service
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        internal static string BuildFacebookPostString(SortedDictionary<string, string> parameters)
        {
            // Build the facebook query from the sorted dictionary of parameters
            StringBuilder facebookPostString = new StringBuilder();
			foreach (string key in parameters.Keys)
			{
				facebookPostString.Append(key + "=" + HttpUtility.UrlEncode(parameters[key]) + "&");
			}

            // chop off the trailing & and return 
            return facebookPostString.Remove(facebookPostString.Length - 1, 1).ToString();
        }

        /// <summary>
        /// Add the default set of parameters required then post off to facebook and return a generic result
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string SendCallToFacebook(SortedDictionary<string, string> parameters)
        {
            return SendCallToFacebook(parameters, null);
        }

        /// <summary>
        /// Add the default set of parameters required then post off to facebook and return a generic result
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string SendCallToFacebook(SortedDictionary<string, string> parameters, Facebook.auth.getSession sessionInfo)
        {
            // Add the usual suspects, these parameters are always required by facebook and can always get tagged on here
            parameters.Add("api_key", WEI_Share.Properties.Resources.FacebookApiKey); // The application's API key 
            parameters.Add("v", WEI_Share.Properties.Resources.FacebookApiVersion); // Version of the API being used 
            parameters.Add("call_id", DateTime.Now.Ticks.ToString()); // unique call id - recommended by facebook to use microtime/milliseconds (e.g. ticks)
            parameters.Add("format", "JSON"); // Using JSON as it is thinner over the wire than XML

            string secret = null;

            if ((sessionInfo != null) && (!string.IsNullOrEmpty(sessionInfo.secret)))
                secret = sessionInfo.secret;
			//else
			//    secret = WEI_Share.Properties.Resources.FacebookSecret;

            // Call this last to sign the parameters with an MD5 hash, then add it to the parameter list
            parameters.Add("sig", Facebook.Security.GenerateFacebookParametersMD5Hash(parameters, secret));

            // send the request down the wire and process the response 
            using (WebClient webRequest = new WebClient())
            {
                string apiCallUrl = String.Format(WEI_Share.Properties.Resources.FacebookApiUrl, BuildFacebookPostString(parameters)); // Format the call string

                string jsonResponse = webRequest.DownloadString(new Uri(apiCallUrl)); // Pass the call string down the web and receive the response

                if (jsonResponse.Contains("\"error_code\"")) // Proces the response for errors - a simple throw is used to convert the text error in to an exception
					throw new Exception("Error posting to Facebook");
                    ////throw new Exception(String.Format("Error calling facebook API!\nJSON: {0} \nAPI CALL: {1}", jsonResponse, apiCallUrl));

                return jsonResponse;
            }
        }


        //internal static WebResponse postRequest(string requestUrl, string postString)
        //{

        //    var webRequest = WebRequest.Create(requestUrl);
        //    webRequest.Method = "POST";
        //    webRequest.ContentType = "application/x-www-form-urlencoded";

        //    if (!String.IsNullOrEmpty(postString))
        //    {
        //        var parameterString = Encoding.ASCII.GetBytes(postString);
        //        webRequest.ContentLength = parameterString.Length;

        //        using (var buffer = webRequest.GetRequestStream())
        //        {
        //            buffer.Write(parameterString, 0, parameterString.Length);
        //            buffer.Close();
        //        }
        //    }

        //    return webRequest.GetResponse();
        //}




        //internal static string processResponse(WebResponse webResponse)
        //{
        //    string xmlResponse;

        //    using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
        //    {
        //        xmlResponse = streamReader.ReadToEnd();
        //    }

        //    ErrorCheck(xmlResponse);

        //    return xmlResponse;
        //}
    }
}